# src/api/appointments.py
from fastapi import APIRouter, HTTPException, status, Query
from typing import List, Optional
from ..models.schemas import AppointmentCreate, AppointmentUpdate, AppointmentOut
from .. import crud

router = APIRouter(tags=["appointments"])


@router.post("", response_model=AppointmentOut, status_code=status.HTTP_201_CREATED)
def create_appointment(payload: AppointmentCreate):
    try:
        appt = crud.create_appointment(payload.dict())
        return appt
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.get("", response_model=List[AppointmentOut])
def list_appointments(date_from: Optional[str] = None, staff_id: Optional[int] = None, patient_id: Optional[int] = None, limit: int = 50, offset: int = 0):
    rows = crud.list_appointments(limit=limit, offset=offset, date_from=date_from, staff_id=staff_id, patient_id=patient_id)
    return rows


@router.get("/{appointment_id}", response_model=AppointmentOut)
def get_appointment(appointment_id: int):
    a = crud.get_appointment(appointment_id)
    if not a:
        raise HTTPException(status_code=404, detail="Appointment not found")
    return a


@router.put("/{appointment_id}", response_model=AppointmentOut)
def update_appointment(appointment_id: int, payload: AppointmentUpdate):
    try:
        updated = crud.update_appointment(appointment_id, payload.dict(exclude_unset=True))
        if not updated:
            raise HTTPException(status_code=404, detail="Appointment not found or no updates applied")
        return updated
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.delete("/{appointment_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_appointment(appointment_id: int):
    count = crud.delete_appointment(appointment_id)
    if count == 0:
        raise HTTPException(status_code=404, detail="Appointment not found")
    return None
